package com.tg.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.appbase.custom.BuildConfig;
import com.appbase.custom.constant.CommonConstants;
import com.base.BaseActivity;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StatusBarUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.builtin.account.RequireVerificationCodeResp;
import com.tg.appcommon.android.AccountValidatorUtil;
import com.tg.appcommon.android.ClickableSpanHelper;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.FontUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.util.ChannelUtil;
import com.tg.login.R;
import com.tg.login.view.TGEditText;
import com.tg.loginex.helper.LoginHelper;
import com.tg.loginex.helper.LoginVerify;

public class ForgotPasswordActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private static final int PERMISSON_REQUESTCODE = 888;
    private static final int PPHONECODE_REQUESTCODE = 999;
    private static final int OVERSEA_LOGIN_REQUEST_CODE = 5858;
    public boolean isFirstRun = true;
    private TGEditText account_edit, code_edit;
    private Button login;
    private String account;
    private int mode = 0;

    private String startType;
    private boolean mIsGetCode = false;
    private CountDownTimer countDownTimer;

    private final LoginHelper mLoginHelper = new LoginHelper();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_forgot_password);
        hideActionBar();
        startType = getIntent().getStringExtra(LoginHelper.START_TYPE);
        StatusBarUtil.setStatusBarTransparent(this);
        initView();
        initData();
    }

    @Override
    public void onBackPressed() {
        TGLog.d(TAG, "onBackPressed");
        backClickListener();
    }


    private void initData() {
        findViewById(R.id.login_new).setVisibility(View.VISIBLE);
        TGLog.d(TAG, "account = " + mLoginHelper.getAccount() + " password = " + mLoginHelper.getPassword());
        isFirstRun = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PPHONECODE_REQUESTCODE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    String code = data.getStringExtra("code");
                    PreferenceUtil.setStringCommit(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_SELECTED_COUNTRY_PHONE_CODE, code);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        super.onRequestPermissionsResult(requestCode, permissions, paramArrayOfInt);
        if (requestCode == ForgotPasswordActivity.PERMISSON_REQUESTCODE) {
            if (!PermissionUtil.verifyPermissions(paramArrayOfInt)) {      //没有授权
                TGLog.d(TAG, "onRequestPermissionsResult = false");
            } else {
                TGLog.d(TAG, "onRequestPermissionsResult = true");
            }
        }
    }

    private void backClickListener() {
        Intent intent = new Intent(ForgotPasswordActivity.this, LoginActivity.class);
        intent.putExtra(LoginHelper.START_TYPE, startType);
        startActivity(intent);
        finish();
    }

    protected void initView() {
        login = findViewById(R.id.login);
        setClickBack(v -> {
            if (mIsGetCode) {
                DialogUtil.openDlalog(ForgotPasswordActivity.this, getString(R.string.register_dialog_tile),
                        null,
                        getString(R.string.confirm),
                        getString(R.string.dialog_cancel), v1 -> doBack(), v12 -> {
                        }, ResourcesUtil.getResources().getColor(R.color.drive_btn_record_selected));
            } else {
                doBack();
            }
        });
        setLoginEnabled(false);
        login.setOnClickListener(this);
        account_edit = findViewById(R.id.editText);
        account_edit.setCodeTextTypeface(FontUtil.getMedium());
        account_edit.setSendCodeClickListener(this);

        code_edit = findViewById(R.id.editText2);
        TextView textView1 = findViewById(R.id.textView);

        try {
            String text = String.format(getResources().getString(R.string.user_register_protocol), getResources().getString(R.string.register));
            textView1.setText(ClickableSpanHelper.getRegisterClickableSpan(text, ForgotPasswordActivity.this));
            textView1.setMovementMethod(LinkMovementMethod.getInstance());
        } catch (Throwable ex) {

        }

        findViewById(R.id.tx_phone).setOnClickListener(v -> {
            findViewById(R.id.tx_phone).setBackgroundResource(R.drawable.white_rounded_bg);
            findViewById(R.id.tx_email).setBackgroundResource(R.color.transparent);
            switchPhone();
        });

        findViewById(R.id.tx_email).setOnClickListener(v -> {
            findViewById(R.id.tx_email).setBackgroundResource(R.drawable.white_rounded_bg);
            findViewById(R.id.tx_phone).setBackgroundResource(R.color.transparent);
            switchEmail();
        });

        findViewById(R.id.back_toolbar).setOnClickListener(v -> {
            backClickListener();
        });
        account_edit.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    setLoginEnabled(false);
                    setCodeEnabled(false);
                } else {
                    String user = s.toString().trim();
                    String code = code_edit.getText();
                    TGLog.d(TAG, "user = " + user);


                    if ((mode == 1 && AccountValidatorUtil.isEmail(user)) || (mode == 0 && AccountValidatorUtil.isMobile(user))) {
                        TGLog.d(TAG, "isEmail = " + AccountValidatorUtil.isEmail(user));
                        TGLog.d(TAG, "isMobile = " + AccountValidatorUtil.isMobile(user));
                        setCodeEnabled((mode == 1 && AccountValidatorUtil.isEmail(user)) || (mode == 0 && AccountValidatorUtil.isMobile(user) && user.length() == 11));

                        if (code.length() == 6) {
                            setLoginEnabled(true);
                        }
                    } else {
                        setLoginEnabled(false);
                        setCodeEnabled(false);
                    }
                }
            }
        });

        InputFilter inputFilter = (source, start, end, dest, dstart, dend) -> {
            if (source.equals(" ")) return "";
            else return null;
        };
        account_edit.setTypeface(FontUtil.getMedium());
        account_edit.setFilters(new InputFilter[]{inputFilter});
        code_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    setLoginEnabled(false);
                } else {
                    String code = s.toString();
                    account = account_edit.getText().trim();
                    if (!TextUtils.isEmpty(account)) {
                        if (AccountValidatorUtil.isMobile(account) && mode == 0) {
                            setLoginEnabled(code.length() == 6);
                        } else {
                            setLoginEnabled(false);
                        }
                    } else {
                        setLoginEnabled(false);
                    }
                }
            }
        });
        code_edit.setTypeface(FontUtil.getMedium());
        String user = getIntent().getStringExtra("account");
        setCodeEnabled(false);
        if (!StringUtils.isEmpty(user)) {
            account_edit.setText(user);
            if (AccountValidatorUtil.isEmail(user) || AccountValidatorUtil.isMobile(user)) {
                setCodeEnabled(true);
            }
        }

        adjustUIHeight();
    }



    private void doBack() {
        if (LoginHelper.TYPE_BIND.equals(startType)) {
            PreferenceUtil.setBoolean(getBaseContext(), CommonConstants.PRE_AUTO_WECHAT_LOGIN, false);

        }
        finish();
    }

    private void setLoginEnabled(boolean enabled) {
        LoginHelper.setButtonEnable(login, enabled);
    }

    private void setCodeEnabled(boolean enabled) {
        if (enabled) {
            boolean b = account_edit.getCodeText().isClickable();
            if (!b) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                    countDownTimer = null;
                }
            }
            account_edit.getCodeText().setText(R.string.get_validate_code);
            account_edit.refreshSendCodeViewLocation();
        }
        account_edit.getCodeText().setClickable(enabled);
        account_edit.getCodeText().setTextColor(enabled ? ResourcesUtil.getResources().getColor(R.color.global_customize_main_color) : ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_gray));
    }


    @Override
    public void onClick(View v) {
        String ac = account_edit.getText().trim();
        String code = code_edit.getText().trim();
        int id = v.getId();
        if (id == R.id.tv_get_code) {
            getVerNum(ac);
        } else if (id == R.id.login || id == R.id.button_with_text) {

            if (ac.length() <= 0) {
                TGToast.showToast(R.string.please_input_account);
                return;
            }
            if (code.length() <= 0) {
                TGToast.showToast(R.string.input_code);
                return;
            }

            if (!AccountValidatorUtil.isEmail(ac) && !AccountValidatorUtil.isMobile(ac)) {
                TGToast.showToast(R.string.account_format_error);
                return;
            }

            if (code.length() != 6) {
                TGToast.showToast(R.string.verify_code_error);
                return;
            }
            verify(ac, code);
        }
    }

    private void switchEmail(){
        mode = 1;
        account_edit.setHint(R.string.email_account);
        account_edit.setText("");
        account_edit.getCodeText().setVisibility(View.VISIBLE);
        account_edit.getCodeText().setText(R.string.get_validate_code);
        account_edit.refreshSendCodeViewLocation();
    }

    private void switchPhone(){
        mode = 0;
        account_edit.setHint(R.string.phone);
        account_edit.setText("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LoginHelper.TYPE_MODIFY_PWD.equals(startType)) {
            return;
        }

        if (mode == 0) {
            account_edit.setHint(R.string.phone);
        } else {
            account_edit.setHint(R.string.email_account);
        }

        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }

        account_edit.getCodeText().setText(R.string.get_validate_code);
        account_edit.refreshSendCodeViewLocation();
        account_edit.getCodeText().setVisibility(View.VISIBLE);
    }

    private boolean bExistUser = false;
    private static final String FORGET = "FORGET";
    private void verify(final String account, final String verifyCode) {
        LoginVerify.verify(account, verifyCode, FORGET, new LoginHelper.LoginListener<String>() {
            @Override
            public void onSuccess(String content) {
                goToPasswordActivity(account, verifyCode);
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                hideLoading();
                TGToast.showToast(errorInfo);
            }

            @Override
            public void onFinish() {
                hideLoading();
            }
        });
    }

    private void goToPasswordActivity(final String account, final String verifyCode) {
        Intent intent = new Intent(ForgotPasswordActivity.this, SetPasswordActivity.class);
        intent.putExtra("account", account);
        intent.putExtra("code", verifyCode);
        intent.putExtra("isForget", true);
        intent.putExtra(CommonConstants.PRE_USER_PWD, getIntent().getStringExtra(CommonConstants.PRE_USER_PWD));
        intent.putExtra(LoginHelper.START_TYPE, startType);
        intent.putExtra(LoginHelper.START_BIND_INFO, getIntent().getStringExtra(LoginHelper.START_BIND_INFO));
        intent.putExtra("isModifyPassword", getIntent().getIntExtra("isModifyPassword", 0));
        startActivity(intent);
    }

    private void setCountDownText() {
        setCodeEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long sec = millisUntilFinished / 1000;
                String src = String.format(getString(R.string.reget_phone_code), sec + "");
                account_edit.getCodeText().setText(src);
                account_edit.refreshSendCodeViewLocation();
            }

            @Override
            public void onFinish() {
                setCodeEnabled(true);
                account_edit.getCodeText().setText(R.string.get_validate_code);
                account_edit.refreshSendCodeViewLocation();
            }
        }.start();
    }


    private void getVerNum(final String account) {
        LoginHelper.passwordRequestCountryPhoneCode(ForgotPasswordActivity.this, account, LoginHelper.PHONE_CODE, new LoginHelper.LoginListener<RequireVerificationCodeResp>() {
            @Override
            public void onSuccess(RequireVerificationCodeResp content) {
                if (content != null){
                    mIsGetCode = true;
                    bExistUser = content.getAccountExist();
                    setCountDownText();
                    TGToast.showToast(R.string.tips_send_code_success);
                }

            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                final TGAlertDialog dialog = new TGAlertDialog(ForgotPasswordActivity.this);
                dialog.builder().setTitle(R.string.dialog_notice)
                        .setCancelable(false).setMessage(errorInfo).setPositiveButton(R.string.message_filter_submit, v -> dialog.cancel()).show();
            }

            @Override
            public void onFinish() {
                hideLoading();
            }
        });
    }


    private void adjustUIHeight(){
        if (LoginHelper.TYPE_REGISTER.equals(startType)) {
            final RelativeLayout relativeLayout = findViewById(R.id.rl_bkg);
            TGLog.d(TAG, "relativeLayout  = " + relativeLayout);
            if (relativeLayout != null){
                relativeLayout.post(() -> {
                    String language = LanguageUtils.getLanguage(getBaseContext());
                    final int MIN_DP_HEIGHT = ((!TextUtils.isEmpty(language) && !language.startsWith("zh")) || !ChannelUtil.isSupportWxPay()) ? 590 : 760;
                    DisplayMetrics dm = new DisplayMetrics();
                    ForgotPasswordActivity.this.getWindowManager().getDefaultDisplay().getRealMetrics(dm);
                    int h = dm.heightPixels;
                    float density = ForgotPasswordActivity.this.getResources().getDisplayMetrics().density;
                    if (density != 0){
                        int minH = (int)(h / density);
                        TGLog.d(TAG, "minH h = " + minH + ", MIN_DP_HEIGHT = " + MIN_DP_HEIGHT);
                        if (minH < MIN_DP_HEIGHT){
                            TGThreadPool.executeOnUiThread(() -> {
                                ViewGroup.LayoutParams layoutParams = relativeLayout.getLayoutParams();
                                TGLog.d(TAG, "layoutParams.height = " + layoutParams.height);
                                layoutParams.height -= DimenUtil.dp2px(ForgotPasswordActivity.this, MIN_DP_HEIGHT - minH);
                                if (layoutParams.height < DimenUtil.dp2px(ForgotPasswordActivity.this, 95)){
                                    layoutParams.height = DimenUtil.dp2px(ForgotPasswordActivity.this, 65);
                                    RelativeLayout relativeLayout1 = findViewById(R.id.rl_toolbar);
                                    TGLog.d(TAG, "relativeLayout1 = " + relativeLayout1);
                                    if (relativeLayout1 != null){
                                        ViewGroup.LayoutParams layoutParams1 = relativeLayout1.getLayoutParams();
                                        TGLog.d(TAG, "layoutParams1 = " + layoutParams1);
                                        if (layoutParams1 instanceof RelativeLayout.LayoutParams){
                                            ((RelativeLayout.LayoutParams)layoutParams1).topMargin = 0;
                                        }
                                        relativeLayout1.setLayoutParams(layoutParams1);
                                    }
                                }
                                TGLog.d(TAG, "layoutParams.height2 = " + layoutParams.height);
                                relativeLayout.setLayoutParams(layoutParams);
                            });
                        }
                    }
                });
            }
        }

    }
}
